package db

import (
	"time"

	"github.com/gomodule/redigo/redis"

	"project/study-go/config"
)

func connRedis() *redis.Pool {
	pool := &redis.Pool{
		Dial: func() (redis.Conn, error) {
			return cedisDial(
				config.Vip.GetString("redis.pool.network"),
				config.Vip.GetString("redis.pool.address"),
				config.Vip.GetString("redis.pool.password"))
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
		MaxIdle:     0,
		IdleTimeout: 0,
	}
	return pool
}

func closeRedis(pool *redis.Pool) error {
	return pool.Close()
}

func cedisDial(network, address, password string) (redis.Conn, error) {
	c, err := redis.Dial(network, address, redis.DialConnectTimeout(time.Second*config.Vip.GetDuration("redis.pool.ConnectTimeout")))
	if err != nil {
		return nil, err
	}
	if password != "" {
		if _, err := c.Do("AUTH", password); err != nil {
			c.Close()
			return nil, err
		}
	}
	return c, err
}

func checkRedis(pool *redis.Pool) error {
	reply, err := RedisPool.Get().Do("ping")
	if reply != "PONG" || err != nil {
		return err
	}
	return nil
}
